package main

import (
	"fmt"
	"zinx-tianjing-study/ziface"
	"zinx-tianjing-study/znet"
)

/*
基于ZINX框架来进行开发服务端应用
*/

// 基础路由
type PingRouter struct {
	znet.BaseRouter
}

// 处理coon业务的主方法
func (p *PingRouter) Handle(request ziface.IRequest) {
	fmt.Println("Call Router Handle...")

	//先读取客户端的数据，再写回自定义数据
	fmt.Println("Recv frome client: msgID:", request.GetMsgID())
	fmt.Println("Recv frome client: data:", string(request.GetRequestData()))

	if err := request.GetConnection().Send(1, request.GetRequestData()); err != nil {
		fmt.Println(err)
	}
}

// 基础路由
type PongRouter struct {
	znet.BaseRouter
}

// 处理coon业务的主方法
func (p *PongRouter) Handle(request ziface.IRequest) {
	fmt.Println("Call Router Handle...")

	//先读取客户端的数据，再写回自定义数据
	fmt.Println("Recv frome client: msgID:", request.GetMsgID())
	fmt.Println("Recv frome client: data:", string(request.GetRequestData()))

	if err := request.GetConnection().Send(1, []byte("Pong!!!!!!")); err != nil {
		fmt.Println(err)
	}
}

func main() {
	s := znet.NewServer("[zinx v0.1]")

	// 注册已有的路由
	s.AddRouter(0, &PingRouter{})
	s.AddRouter(1, &PongRouter{})

	// 注册文件上传路由
	fileRouter := znet.NewFileUploadRouter()
	s.AddRouter(ziface.MsgIDFileStartUpload, fileRouter)
	s.AddRouter(ziface.MsgIDFileChunkUpload, fileRouter)
	s.AddRouter(ziface.MsgIDFileUploadFinish, fileRouter)

	s.SetOnConnStart(func(i ziface.IConnection) {
		fmt.Println("前置hook函数执行.....")
	})
	s.SetOnConnStop(func(i ziface.IConnection) {
		fmt.Println("后置hook函数执行.....")
	})

	s.Serve()
}
